package org.apimgr.service;

import com.alibaba.fastjson.JSON;
import org.apimgr.entity.ApiUser;
import org.apimgr.enums.PTExceptionCode;
import org.apimgr.exception.PTUnCheckedException;
import org.apimgr.mapper.ApiUserMapper;
import org.apimgr.util.CommonsUtil;
import org.apimgr.util.JedisUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * Created by yangjie on 2017/8/2.
 * 登录Service
 */
@Service
public class LoginService {

    @Resource
    private ApiUserMapper apiUserMapper;

    @Resource
    private JedisUtil jedisUtil;

    /**
     * 根据token获取用户对象
     * @param token
     * @return
     */
    public ApiUser getLoginUser(String token){
        if(CommonsUtil.isStringEmpty(token)){
            throw  new PTUnCheckedException(PTExceptionCode.SYS_AUTH_TOKEN_ERROR.getCode());
        }

        ApiUser apiUser = JSON.parseObject(jedisUtil.get(token),ApiUser.class);
        if(apiUser == null){
            throw  new PTUnCheckedException(PTExceptionCode.SYS_AUTH_TOKEN_ERROR.getCode());
        }else{
            jedisUtil.expilre(token,30);
        }
        return  apiUser;
    }


    public void loginOut(String token){
        if(CommonsUtil.isStringEmpty(token)){
            throw  new PTUnCheckedException(PTExceptionCode.SYS_AUTH_TOKEN_ERROR.getCode());
        }
        jedisUtil.del(token);
    }

}
